package org.obm.lmtp;

import java.util.LinkedList;
import java.util.List;

import org.eclipse.core.runtime.Plugin;
import org.obm.lmtp.backend.IDeliveryAgent;
import org.obm.lmtp.backend.ILmtpBackendFactory;
import org.obm.lmtp.backend.IMailboxValidator;
import org.obm.lmtp.impl.BiggLmtpBackend;
import org.osgi.framework.BundleContext;

import fr.aliasource.utils.RunnableExtensionLoader;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends Plugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "org.obm.lmtp";

	// The shared instance
	private static Activator plugin;

	private BiggLmtpBackend backend;

	/**
	 * The constructor
	 */
	public Activator() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.core.runtime.Plugins#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;

		List<IMailboxValidator> validators = new LinkedList<IMailboxValidator>();
		List<IDeliveryAgent> agents = new LinkedList<IDeliveryAgent>();

		try {
			RunnableExtensionLoader<ILmtpBackendFactory> rel = new RunnableExtensionLoader<ILmtpBackendFactory>();
			List<ILmtpBackendFactory> l = rel.loadExtensions(PLUGIN_ID,
					"lmtpbackendfactory", "lmtp_backend_factory",
					"implementation");
			for (ILmtpBackendFactory f : l) {
				IMailboxValidator validator = f.getValidator();
				if (validator != null) {
					validators.add(validator);
				}
				IDeliveryAgent agent = f.getDeliveryAgent();
				if (agent != null) {
					agents.add(agent);
				}
			}
		} catch (Throwable t) {
			t.printStackTrace();
		}
		backend = new BiggLmtpBackend(validators, agents);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 * 
	 * @return the shared instance
	 */
	public static Activator getDefault() {
		return plugin;
	}

	public BiggLmtpBackend getBackend() {
		return backend;
	}

}
